package edu.hawaii.halealohacli;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Current-power class that get the current power based on the tower name.
 * 
 * @author John MacMillan
 * @author Mitchell Kupfer
 * @author Bryson Hori
 */
public class CurrentPower {
  protected String tower;
  WattDepotClient client;

  /**
   * Default constructor.
   * 
   * @param tower the tower we want to get the current power for.
   * @param client the WattDepot client.
   */
  public CurrentPower(String tower, WattDepotClient client) {
    this.tower = tower;
    this.client = client;
  }

  /**
   * Simple accessor method to get the value of tower of the tower name.
   * 
   * @return Returns the value of tower.
   */
  public String getTower() {
    return this.tower;
  }

  /**
   * Runs the actual command.
   * 
   * @throws Exception If problem occurs when running through data from server.
   * @return a boolean, true if command is successful.
   */
  public boolean run() throws Exception {
    boolean value = false;
    List<Source> sources = this.client.getSources();
    String sourceName;
    SensorData data;
    XMLGregorianCalendar timestamp;
    Format format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    Date date;
    double powerConsumed;

    // goes through the all of the sources looking for right tower name.
    for (Source source : sources) {
      sourceName = source.getName();
      // finds the right tower name through comparison.
      if (sourceName.compareTo(this.tower) == 0) {
        data = this.client.getLatestSensorData(sourceName);
        timestamp = data.getTimestamp();
        // get poser consumed based on the lasted sensor data.
        powerConsumed = client.getPowerConsumed(sourceName, timestamp);
        // converts the time-stamp from latest sensor data to a date object.
        date = timestamp.toGregorianCalendar().getTime();
        // Prints out the found corresponding data to the tower name.
        System.out.format("%s's power as of %s was %s kW\n", sourceName, format.format(date),
            powerConsumed / 1000);

        value = true;
      }
    }
    return value;
  }
}
